/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* build(vector<int>& preorder, vector<int>& inorder,int& idx,int midBegin,int midEnd){

        if(idx>=preorder.size() || midBegin>midEnd){

            return nullptr;
        }
        TreeNode* curRoot=new TreeNode(preorder[idx]);
        int tmpBegin=midBegin;
        while(preorder[idx]!=inorder[tmpBegin]){

            ++tmpBegin;
        }
        ++idx;
        TreeNode* leftNode=build(preorder,inorder,idx,midBegin,tmpBegin-1);
        TreeNode* rightNode=build(preorder,inorder,idx,tmpBegin+1,midEnd);

        curRoot->left=leftNode;
        curRoot->right=rightNode;
        return curRoot;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        
        int idx=0;
        return build(preorder,inorder,idx,0,inorder.size()-1);
    }
};
